import requests
import json

beaver = 'Bearer bce-v3/ALTAK-uActZcRDqp7vszvgMXCmT/00537916b888bc8dde87c88e074fdbb39d90d05d'
app_id = "8e6261af-1425-43cb-be2c-f6a572c5419c"

# 步骤二：上传文件
url = "https://qianfan.baidubce.com/v2/app/conversation/file/upload"

payload = {
    'app_id': app_id
}
files = [
    ('file', ('课堂图片.jpg', open('D:\学习作业\专业实习-张青\课堂图片.jpg', 'rb'), 'image/jpeg'))
]
headers = {
    'X-Appbuilder-Authorization': beaver
}

response = requests.post(url, headers=headers, data=payload, files=files)
print(response.text)

# 提取file_id
response_data = json.loads(response.text)
file_id = response_data['id']
print("输出的图片id为 :" + file_id)

# 步骤一：上传对话
url = "https://qianfan.baidubce.com/v2/app/conversation"

payload = json.dumps({
    "app_id": app_id
})
headers = {
    'Content-Type': 'application/json',
    'X-Appbuilder-Authorization': beaver
}

response = requests.post(url, headers=headers, data=payload)

print(response.text)

# 提取conversation_id
response_data = json.loads(response.text)
conversation_id = response_data['conversation_id']
print("输出的会话id："+conversation_id)

# 步骤三：执行对话
url = "https://qianfan.baidubce.com/v2/app/conversation/runs"

payload = json.dumps({
    "app_id": app_id,
    "query": input("请输入问题"),
    "stream": False,
    "conversation_id": conversation_id,
})
headers = {
    'Content-Type': 'application/json',
    'X-Appbuilder-Authorization': beaver
}

response = requests.post(url, headers=headers, data=payload)

print(response.text)

# 提取答案
response_data = json.loads(response.text)
answer = response_data['answer']

# 写入答案到文件
with open("answer.txt", 'a') as file:
    file.write(f"{answer}\n")